package com.hao.gulimall.product.exception;

import com.hao.common.exception.BizCodeEnume;
import com.hao.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chenwenhao
 * @version 1.0.0
 * @ClassName GuliMallControllerAdvice.java
 * @Description
 * @createTime 2020/7/20,19:25
 *      统一异常处理类，并使用枚举类的统一异常状态码
 *      @Slf4j：日志
 */
@Slf4j
//@ResponseBody
//@ControllerAdvice(basePackages = "com.hao.gulimall.product.controller")
@RestControllerAdvice(basePackages = "com.hao.gulimall.product.controller")
public class GuliMallControllerAdvice {

    /**
     * 处理数据校验异常，精准匹配异常
     *
     * @param e e
     * @return {@link R}
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出错：" + e.getMessage() + "异常类型：" + e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String,String> map = new HashMap<>();
            //获取校验错误结果
            result.getFieldErrors().forEach((item) ->{
                //错误提示和属性名
                String message = item.getDefaultMessage();
                String field = item.getField();
                map.put(field,message);
            });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",map);
    }


    /**
     * 处理异常
     *      无法精准匹配异常时，使用这个异常处理
     * @param throwable throwable
     * @return {@link R}
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){

        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }


}
